package com.intel.factorytest.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;

import com.intel.factorytest.R;

public class Bluetooth extends Activity{
    private static final String TEST_ITEM = "test_item";
          private static final String TEST_ITEM_RESULT = "test_item_result";
    private BluetoothAdapter mAdapter = null; 
    private static final int SET_BT_STATUS = 1;
    private Timer mTimer;
    private IntentFilter mFilter = null;
        private BroadcastReceiver mReceiver;
    private TextView btText = null;
    private boolean is_pass = false;
    private long mLastScan;
    private int mdeviceCount = 0;
    private static final int SCAN_EXPIRATION_MS = 10 * 1000;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == SET_BT_STATUS){
                if(BluetoothAdapter.STATE_ON != mAdapter.getState()) {
                    mAdapter.enable();
                } else {
                    startScanning(true);
                }
            }

        }
    }; 
    public void onCreate(Bundle b){
        super.onCreate(b);
        Intent intent = getIntent();
        String orientationStr = intent.getStringExtra("sd_orientation");
        int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        Log.i("util","orientationStr = " + orientationStr);
        if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            super.setRequestedOrientation(orientation);

        } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            super.setRequestedOrientation(orientation);

        }
        mFilter = new IntentFilter();
            mFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mFilter.addAction(BluetoothDevice.ACTION_FOUND);
        mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //mFilter.addAction(BluetoothDevice.ACTION_DISAPPEARED);
            mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                handleEvent(context, intent);
            }
        };

            mAdapter = BluetoothAdapter.getDefaultAdapter();
        btText = new TextView(this);
        btText.setTextSize(24.0f);
        btText.setGravity(Gravity.CENTER);
        btText.setText(this.getString(R.string.SERVICEMENU_BT_SEARCH_TXT));
        setContentView(btText);
        
    
     }

    protected void onResume() {
        super.onResume();
        Bluetooth.this.registerReceiver(mReceiver, mFilter, "permission.CIT_ALLOW_BROADCAST", null);
        mTimer = new Timer();
        mTimer.schedule(new TimerTask(){
            @Override
            public void run() {
                mHandler.sendEmptyMessage(SET_BT_STATUS);
            }
    
        }, 1000);    


    }

    private void handleEvent(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i("meilianggang", "action = " + action);
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                updateBlueToothState(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR));
            Log.i("meilianggang", "updateBlueToothState");

        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
        } else if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            mdeviceCount++;
            String tmpStr = this.getString(R.string.SERVICEMENU_BT_OPEN_TXT) + "\n" + this.getString(R.string.SERVICEMENU_BT_SCAN_RESULT_TXT) + mdeviceCount;
            tmpStr +=  "\n" + this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_TXT); 
            btText.setText(tmpStr);
            Log.i("meilianggang", "results.size() = " + mdeviceCount);
            is_pass = true;


        } /*else if(BluetoothDevice.ACTION_DISAPPEARED.equals(action)) {
            if(mdeviceCount > 0) {
                mdeviceCount--;
            }
            String tmpStr = this.getString(R.string.SERVICEMENU_BT_OPEN_TXT) + "\n" + this.getString(R.string.SERVICEMENU_BT_SCAN_RESULT_TXT) + mdeviceCount;
            tmpStr +=  "\n" + this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_TXT); 
            btText.setText(tmpStr);
            Log.i("meilianggang", "results.size() = " + mdeviceCount);

        }*/
    }
    private void updateBlueToothState(int state) {
        switch (state) {
            case BluetoothAdapter.STATE_ON:
            btText.setText(this.getString(R.string.SERVICEMENU_BT_OPEN_TXT));
            startScanning(false);
            return; 
            case BluetoothAdapter.STATE_OFF:
            is_pass = false;
            btText.setText(this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_FAIL_TXT));
            break;
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        this.unregisterReceiver(mReceiver);
    }
    void startScanning(boolean force) {
        if (!mAdapter.isDiscovering()) {
            if (!force) {
            // Don't scan more than frequently than SCAN_EXPIRATION_MS,
            // unless forced
            if (mLastScan + SCAN_EXPIRATION_MS > System.currentTimeMillis()) {
                return;
            }
            }

            if (mAdapter.startDiscovery()) {
            mLastScan = System.currentTimeMillis();
            }
        }
    }


    private void setTestResult () {
        Intent intent = new Intent();
        Intent mIntent = getIntent();
        int pos = mIntent.getIntExtra(TEST_ITEM,-1);
        intent.putExtra(TEST_ITEM,pos);
        intent.putExtra(TEST_ITEM_RESULT,is_pass);
        setResult(0, intent);
    }
    @Override
    public void finish() {
        setTestResult (); 
        super.finish();
    }
}
    
